<template>
  <div class="user-container">
    <el-card class="user-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">个人信息设置</span>
        </div>
      </template>
      <el-form
        :model="userInfoSetForm"
        label-position="top"
        class="compact-form"
        :rules="userInfoSetRules"
        :ref="(el:any)=>{userInfoSetRef=el}"
      >
        <el-form-item label="用户名" required prop="username">
          <el-input
            v-model="userInfoSetForm.username"
            placeholder="新用户名"
            clearable
            suffix-icon="el-icon-user"
          />
        </el-form-item>
        <el-form-item label="电子邮箱" required prop="email">
          <el-input
            v-model="userInfoSetForm.email"
            placeholder="example@domain.com"
            clearable
            suffix-icon="el-icon-message"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" required prop="password">
          <el-input
            v-model="userInfoSetForm.password"
            type="password"
            show-password
            placeholder="新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" required prop="confirmPassword">
          <el-input
            v-model="userInfoSetForm.confirmPassword"
            type="password"
            show-password
            placeholder="再次输入密码"
          />
        </el-form-item>
        <div class="form-actions">
          <el-button type="primary" icon="el-icon-check" @click="handleSave"
            >保存更改</el-button
          >
        </div>
      </el-form>
    </el-card>
    <el-card class="feedback-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">意见反馈</span>
          <el-tag type="info" size="small">建议与问题</el-tag>
        </div>
      </template>
      <el-form
        label-position="top"
        :model="feedbackSetForm"
        :rules="feedbackSetRules"
        :ref="(el:any)=>{feedbackSetRef=el}"
      >
        <el-form-item label="提交反馈" prop="feedback">
          <el-input
            v-model="feedbackSetForm.feedback"
            type="textarea"
            :autosize="{ minRows: 4 }"
            placeholder="请输入您的宝贵意见或遇到的问题..."
            resize="none"
          />
        </el-form-item>
        <el-form-item>
          <div class="form-actions">
            <el-button
              type="success"
              icon="el-icon-position"
              @click="handleFeedback"
              :disabled="!feedbackSetForm.feedback"
              >提交反馈</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, nextTick, onMounted } from "vue";
const instance = getCurrentInstance();
const proxy = instance?.proxy as any;
import { useRouter, Router } from "vue-router";
const router: Router = useRouter();
import verify from "@/utils/verify";

import { useUserStore } from "@/stores/userStore";
const userStore = useUserStore();

//表单接口
import { UserInfoSet, FeedbackSet } from "@/types/form";
import { RequestParams } from "@/types/request";
import { UserInfo } from "@/types/user";
import { ElForm } from "element-plus";

const userData: UserInfo = userStore.getUserData();
const token = ref<string>("");
const userId = ref<number | null>();

const emit = defineEmits(["username-change"]);

//表单变量
const userInfoSetForm = ref<UserInfoSet>({
  username: "",
  password: "",
  email: "",
  confirmPassword: "",
});
const feedbackSetForm = ref<FeedbackSet>({
  feedback: "",
});

const userInfoSetRef = ref<InstanceType<typeof ElForm> | null>(null);
const feedbackSetRef = ref<InstanceType<typeof ElForm> | null>(null);

//校验
const userInfoSetRules = ref({
  username: [
    {
      validator: verify.username,
      message: "用户名格式不正确，必须是4-16个字符，只能包含数字、字母和下划线",
      trigger: "blur",
    },
  ],
  email: [
    {
      validator: verify.email,
      message: "请输入有效的邮箱地址",
      trigger: "blur",
    },
  ],
  password: [
    {
      validator: verify.password,
      message:
        "密码格式不正确，必须至少8个字符，包含一个数字、一个大写字母、一个小写字母和一个特殊字符",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      validator: (_: any, value: string, callback: (error?: Error) => void) => {
        checkConfirmPassword(value, callback, userInfoSetForm.value.password);
      },
      trigger: "blur",
    },
  ],
});

const feedbackSetRules = ref({
  feedback: [
    { min: 1, max: 100, message: "反馈控制在1-100个字符", trigger: "blur" },
  ],
});

const checkConfirmPassword = (
  value: string,
  callback: (error?: Error) => void,
  password: string
) => {
  if (value) {
    if (value === password) {
      callback();
    } else {
      callback(new Error("两次输入密码不一致"));
    }
  } else {
    callback(new Error("请输入确认密码"));
  }
};

//提交
const handleSave = async () => {
  await nextTick();
  const userInfoInstance = userInfoSetRef.value;
  if (!userInfoInstance) return;
  try {
    await userInfoInstance.validate();
    const data: RequestParams = {
      username: userInfoSetForm.value.username,
      password: userInfoSetForm.value.password,
      email: userInfoSetForm.value.email,
    };
    let result: any = await proxy.request({
      method: "post",
      url: proxy.api.usersUpdateSelf,
      data: data as RequestParams,
      headers: {
        authentication: token.value,
        "Content-Type": "application/json",
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      proxy.message.success("用户信息已保存");
      //更新用户名
      emit("username-change", userInfoSetForm.value.username);
      const sessionUserData = sessionStorage.getItem("userData");
      const userData: UserInfo = sessionUserData
        ? JSON.parse(sessionUserData)
        : ({} as UserInfo);
      //更改密码了就退出

      userData.username = userInfoSetForm.value.username;
      userData.email = userInfoSetForm.value.email;
      sessionStorage.setItem("userData", JSON.stringify(userData));
    } else if (result.code === 401) {
      proxy.message.warning("登录已过期，请重新登录");
      sessionStorage.removeItem("userData");
      router.push("/login");
    } else {
      proxy.message.error("保存失败");
    }
  } catch (error: any) {
    if (error.response?.data?.code === 401) {
      proxy.message.error("登录已过期，请重新登录");
      sessionStorage.removeItem("userData");
      router.push("/login");
    } else {
      proxy.message.error("保存失败");
    }
  }
};
const handleFeedback = async () => {
  await nextTick();
  const feedbackInstance = feedbackSetRef.value;
  if (!feedbackInstance) return;
  try {
    await feedbackInstance.validate();
    const data: RequestParams = {
      content: feedbackSetForm.value.feedback,
    };
    let result: any = await proxy.request({
      method: "post",
      url: proxy.api.usersFeedback,
      data: data as RequestParams,
      headers: {
        authentication: token.value,
        "Content-Type": "application/json",
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      proxy.message.success("反馈已提交");
      feedbackSetForm.value.feedback = "";
    } else {
      proxy.message.warning("反馈提交失败，请检查网络连接");
    }
  } catch (error: any) {
    proxy.message.warning("反馈提交失败，请检查网络连接");
  }
};

onMounted(() => {
  if (userData) {
    userInfoSetForm.value.username = userData.username;
    userInfoSetForm.value.email = userData.email;
    token.value = userData.token;
    userId.value = userData.userId;
  }
});
</script>

<style scoped>
.user-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 15px;
}

.user-card,
.feedback-card {
  margin-bottom: 24px;
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.user-card:hover,
.feedback-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.compact-form {
  padding: 0 8px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #5c6b7a;
}

.el-textarea ::placeholder {
  color: #c0c4cc;
  font-style: italic;
}

.el-button {
  border-radius: 8px;
  padding: 10px 24px;
  letter-spacing: 0.5px;
}

.el-button [class*="el-icon-"] {
  margin-right: 6px;
}

.el-input {
  font-size: 14px;
}
</style>
